package pers.ijfxu.testngext.dataprovider.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import pers.ijfxu.testngext.utils.JsonUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static java.util.Objects.isNull;

/**
 * excel 文本迭代器
 *
 * @author ijfxu  
 * @since 2021/3/22 00:17
 * @see TxtIterator
 */
public class ExcelIterator implements Iterator<Object[]> {
    private ExcelReader reader;
    private Integer rowCount;
    private Integer rowIndex = 0;

    /**
     * 构造器
     *
     * @param dataFile excel文本路径 
     * @author ijfxu
     * @since 2021/3/22 00:17
     */
    public ExcelIterator(String dataFile) {
        this.reader = ExcelUtil.getReader(dataFile);
        this.rowCount = reader.getRowCount();
    }

    @Override
    public boolean hasNext() {
        return rowCount > rowIndex;
    }

    @Override
    public Object[] next() {
        if (!hasNext()) {
            reader.close();
            return null;
        }
        rowIndex++;
        List<Map<String, Object>> datas = reader.read(0, rowIndex, rowIndex);    // 读取一行数据
        if (isNull(datas) || datas.size() <= 0) {
            rowIndex = rowCount;
            return null;
        }
        return parseData(datas.get(0));
    }

    /**
     * 解析数据，提供继承重写
     *
     * @param data excel map 数据
     * @return Object[] map数据组 
     * @author ijfxu
     * @since 2021/3/22 00:17
     */
    public Object[] parseData(Map<String, Object> data) {
        String[] dataArr = new String[1];
        dataArr[0] = JsonUtils.toJsonStr(data);
        return dataArr;
    }

}
